using System;
using System.Runtime.InteropServices;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;

namespace Mystery.SharePoint.Features.MetadataRequired
{
    /// <summary>
    /// This class handles events raised during feature activation, deactivation, installation, uninstallation, and upgrade.
    /// </summary>
    /// <remarks>
    /// The GUID attached to this class may be used during packaging and should not be modified.
    /// </remarks>

    [Guid("31ef4f1c-4b88-46ed-9761-38d76e0d142c")]
    public class MetadataRequiredEventReceiver : SPFeatureReceiver
    {
        private const string MetadataProviderKey = "MetadataProvider";

        public override void FeatureActivated(SPFeatureReceiverProperties properties)
        {
            SPSite site = properties.Feature.Parent as SPSite;

            string providerName = properties.Feature.Properties.Read(MetadataProviderKey, string.Empty);
            if (providerName == string.Empty)
            {
                throw new InvalidOperationException("MetadataProvider has not been specified");
            }

            SiteMetadata md = ProvisioningUtilities.CreateObjectFromString<SiteMetadata>(providerName, site);

            site.SetMetadataProvider(md.GetType());
            site.RootWeb.Properties.Update();
        }
    }
}
